<?php

namespace app\pay\service;

use AlipayTradeWapPayRequest;
use AopClient;
use app\common\exception\BusinessException;
use app\common\model\AppConfig;
use stdClass;

class AliPayService extends PayService
{
    public function getInstance()
    {
        $config = $this->getAppConfig();
        $aop = new AopClient ();
        $aop->appId = $config['appId'];
        $aop->gatewayUrl = $config['gatewayUrl'];
        $aop->rsaPrivateKey = $config['rsaPrivateKey'];
        $aop->alipayrsaPublicKey = $config['rsaPublicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        return $aop;
    }

    /**
     * getAppConfig
     * @throws BusinessException
     */
    public function getAppConfig(): array
    {
        if (!empty($this->appConfig)) {
            return $this->appConfig;
        }
        $appConfigModel = new AppConfig();
        $this->appConfig = $appConfigModel->getByIdAndType($this->appId, 'ali_h5_pay');
        if (!$this->appConfig) {
            throw new BusinessException('此应用未配置支付宝H5支付参数');
        }
        return $this->appConfig;
    }

    /**
     * buildPayData(支付宝H5支付)
     */
    public function buildPayData(string $out_trade_no, float $total_fee, string $goods_name): string
    {
        // 获取实例
        $aop = $this->getInstance();

        /******必传参数******/
        $object = new stdClass();
        $object->out_trade_no = $out_trade_no;
        $object->total_amount = $total_fee;
        $object->subject = $goods_name;

        $json = json_encode($object);
        $request = new AlipayTradeWapPayRequest();
        //异步接收地址
        $request->setNotifyUrl($this->appConfig['notifyUrl']);
        //同步跳转地址
        //$request->setReturnUrl($this->appConfig['returnUrl']);
        $request->setBizContent($json);
        $pageRedirectionData = $aop->pageExecute($request, "POST");

        //保存网页支付数据到缓存
        $this->createWebPayDataToCache($out_trade_no, $pageRedirectionData);

        //返回
        return $this->createWebPayUrl($out_trade_no);
    }

    /**
     * checkSign
     * @param array $params
     * @return bool
     * @throws
     */
    public function checkSign(array $params): bool
    {
        // 获取实例
        $aop = $this->getInstance();

        // 验签
        return $aop->rsaCheckV1($params, null);
    }

}